package com.mm.serivce.quartz.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mm.base.forest.OtherClient;
import com.mm.base.forest.ShaDiaoClient;
import com.mm.base.lunar.Solar;
import com.mm.domain.common.DCommonCode;
import com.mm.domain.quartz.WeatherVo;
import com.mm.serivce.quartz.ShaDiaService;
import com.mm.serivce.common.IDCommonCodeService;
import com.mm.util.common.RedisUtil;
import com.mm.util.note.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 描述: 获取第三方语录
 *
 * @author: yanglin
 * @Date: 2021-07-16-9:03
 * @Version: 1.0
 */
@Slf4j
@Service
public class ShaDiaServiceImpl implements ShaDiaService {

    private final ShaDiaoClient shaDiaoClient;

    private final OtherClient otherClient;

    private final IDCommonCodeService codeService;

    private final RedisUtil redisUtil;

    public ShaDiaServiceImpl(ShaDiaoClient shaDiaoClient, OtherClient otherClient, IDCommonCodeService codeService, RedisUtil redisUtil) {
        this.shaDiaoClient = shaDiaoClient;
        this.otherClient = otherClient;
        this.codeService = codeService;
        this.redisUtil = redisUtil;
    }

    @Override
    public String querySdAna() {
        StringBuilder sb = new StringBuilder();
        sb.append(" <p> ").append("早上好!&nbsp;Alone.");
        sb.append(" <p> ").append(queryWorkInfoTwo(null));
        sb.append(" <br> ");
        sb.append(" <br> ");
        Solar date = new Solar();
        sb.append(" <p> ").append("[阳历]");
        sb.append(" <p> ").append(date.toFullString()).append(" <p> ");
        sb.append(" <br> ");
        sb.append(" <p> ").append("[阴历]");
        sb.append(" <p> ").append(date.getLunar().toFullString()).append(" <p> ");
        sb.append(" <br> ");
        sb.append(" <p> ").append("[天气]");
        sb.append(" <p> ").append(this.mergeManyWeatherDay(0)).append(" <p> ");
        sb.append(" <br> ");
        StringBuilder duStr = new StringBuilder();
        duStr.append(" <p> ").append("[语录-毒鸡汤]");
        sb.append(this.mergeShaDiaoTxt(1, "note:shadiao:du", duStr));
        StringBuilder chpStr = new StringBuilder();
        chpStr.append(" <p> ").append(" <br> ").append("[语录-彩虹屁]");
        sb.append(this.mergeShaDiaoTxt(0, "note:shadiao:chp", chpStr));
        StringBuilder friendStr = new StringBuilder();
        friendStr.append(" <p> ").append(" <br> ").append("[语录-朋友圈]");
        sb.append(this.mergeShaDiaoTxt(2, "note:shadiao:friend", friendStr));
        StringBuilder commentStr = new StringBuilder();
        commentStr.append(" <p> ").append(" <br> ").append("[语录-网易云]");
        sb.append(this.mergeWYYComment("note:netease:comment", commentStr));
        StringBuilder poetryStr = new StringBuilder();
        poetryStr.append(" <p> ").append(" <br> ").append("[语录-诗词]");
        sb.append(this.mergePoetryComment("note:poetry:comment", poetryStr));
        StringBuilder playBoyStr = new StringBuilder();
        playBoyStr.append(" <p> ").append(" <br> ").append("[语录-渣男]");
        sb.append(this.mergePlayBoyTxt("note:playboy:comment", playBoyStr));
        StringBuilder teaStr = new StringBuilder();
        teaStr.append(" <p> ").append(" <br> ").append("[语录-绿茶]");
        sb.append(this.mergeGreenTeaTxt("note:tea:comment", teaStr));
        StringBuilder jestStr = new StringBuilder();
        jestStr.append(" <p> ").append(" <br> ").append("[语录-笑话]");
        sb.append(this.mergeJestTxt("note:jest:comment", jestStr));
        StringBuilder newsStr = new StringBuilder();
        newsStr.append(" <p> ").append(" <br> ").append("[新闻-每日资讯]");
        sb.append(this.mergeNewsTxt("note:news:comment", newsStr));
        sb.append(" <p> ").append(" <br> ");
        sb.append(getRandomImg());
        sb.append(" <br> ");
        sb.append(" <p> ").append("[新的一天也要继续加油哦！]");
        return sb.toString();
    }

    @Override
    public String querySdAna(String dateStr, int day) {
        StringBuilder sb = new StringBuilder();
        sb.append(" <p> ").append("早上好!&nbsp;Alone.");
        sb.append(" <p> ").append(queryWorkInfoTwo(dateStr));
        sb.append(" <br> ");
        Solar date = new Solar();
        sb.append(" <p> ").append("[阳历]");
        sb.append(" <p> ").append(date.next(day).toFullString()).append(" <p> ");
        sb.append(" <br> ");
        sb.append(" <p> ").append("[阴历]");
        sb.append(" <p> ").append(date.getLunar().next(day).toFullString()).append(" <p> ");
        sb.append(" <br> ");
        sb.append(" <p> ").append("[天气]");
        sb.append(" <p> ").append(this.mergeManyWeatherDay(day)).append(" <p> ");
        sb.append(" <br> ");
        StringBuilder duStr = new StringBuilder();
        duStr.append(" <p> ").append("[语录-毒鸡汤]");
        sb.append(this.mergeShaDiaoTxt(1, "note:shadiao:du", duStr));
        StringBuilder chpStr = new StringBuilder();
        chpStr.append(" <p> ").append(" <br> ").append("[语录-彩虹屁]");
        sb.append(this.mergeShaDiaoTxt(0, "note:shadiao:chp", chpStr));
        StringBuilder friendStr = new StringBuilder();
        friendStr.append(" <p> ").append(" <br> ").append("[语录-朋友圈]");
        sb.append(this.mergeShaDiaoTxt(2, "note:shadiao:friend", friendStr));
        StringBuilder commentStr = new StringBuilder();
        commentStr.append(" <p> ").append(" <br> ").append("[语录-网易云]");
        sb.append(this.mergeWYYComment("note:netease:comment", commentStr));
        StringBuilder poetryStr = new StringBuilder();
        poetryStr.append(" <p> ").append(" <br> ").append("[语录-诗词]");
        sb.append(this.mergePoetryComment("note:poetry:comment", poetryStr));
        StringBuilder playBoyStr = new StringBuilder();
        playBoyStr.append(" <p> ").append(" <br> ").append("[语录-渣男]");
        sb.append(this.mergePlayBoyTxt("note:playboy:comment", playBoyStr));
        StringBuilder teaStr = new StringBuilder();
        teaStr.append(" <p> ").append(" <br> ").append("[语录-绿茶]");
        sb.append(this.mergeGreenTeaTxt("note:tea:comment", teaStr));
        StringBuilder jestStr = new StringBuilder();
        jestStr.append(" <p> ").append(" <br> ").append("[语录-笑话]");
        sb.append(this.mergeJestTxt("note:jest:comment", jestStr));
        StringBuilder newsStr = new StringBuilder();
        newsStr.append(" <p> ").append(" <br> ").append("[新闻-每日资讯]");
        sb.append(this.mergeNewsTxt("note:news:comment", newsStr));
        sb.append(" <p> ").append(" <br> ");
        sb.append(getRandomImg());
        sb.append(" <br> ");
        sb.append(" <p> ").append("[新的一天也要继续加油哦！]");
        return sb.toString();
    }

    @Override
    public String queryWeatherDay(Integer cityCode) {
        String weatherStr = null;
        String redisKey = "weather:" + cityCode;
        String redisBackKey = "weather:back:" + cityCode;
        // Redis 存储
        if (redisUtil.hasKey(redisKey)) {
            Object o = redisUtil.hget(redisKey, cityCode.toString());
            if (o != null) {
                weatherStr = o.toString();
            }
        } else {
            try {
                weatherStr = otherClient.queryWeatherDay(cityCode);
                redisUtil.hset(redisKey, cityCode.toString(), weatherStr, RedisUtil.TIME);
                redisUtil.hset(redisBackKey, cityCode.toString(), weatherStr, RedisUtil.TASK_TIME);
            } catch (Exception e) {
                Object o = redisUtil.hget(redisBackKey, cityCode.toString());
                if (o != null) {
                    weatherStr = o.toString();
                    long keyBackTime = redisUtil.getExpire(redisBackKey);
                    redisUtil.hset(redisBackKey, cityCode.toString(), weatherStr, keyBackTime);
                }
            }
        }

        return weatherStr;
    }

    /**
     * {
     * "nowtime":"2021年3月31日" #现在时间
     * "Todayweek":"星期三" #今天周几
     * "monthweek":"5" #本月第几周
     * "Otherweek":"星期三" #指定日期周几
     * }
     *
     * @param dateStr
     * @return
     */
    @Override
    public String queryWeekInfo(String dateStr) {
        // 今天星期一,本月第5周
        StringBuilder sb = new StringBuilder();
        if (StrUtil.isBlank(dateStr)) {
            dateStr = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        }
        String todayWeek = "星期一";
        String monthWeek = "5";
        String currentWeek = otherClient.queryWeekInfo(dateStr);
        if (StrUtil.isBlank(currentWeek)) {
            JSONObject jsonObject = JSONUtil.parseObj(currentWeek);
            if (Objects.nonNull(jsonObject)) {
                // 今天周几
                todayWeek = jsonObject.get("Todayweek").toString();
                // 本月第几周
                monthWeek = jsonObject.get("monthweek").toString();
            }
        }
        sb.append("今天").append(todayWeek).append(",本月第").append(monthWeek).append("周");
        return sb.toString();
    }

    /**
     * {
     * "code": 0,              // 0服务正常。-1服务出错
     * "type": {
     * "type": enum(0, 1, 2, 3), // 节假日类型，分别表示 工作日、周末、节日、调休。
     * "name": "周六",         // 节假日类型中文名，可能值为 周一 至 周日、假期的名字、某某调休。
     * "week": enum(1 - 7)    // 一周中的第几天。值为 1 - 7，分别表示 周一 至 周日。
     * },
     * "holiday": {
     * "holiday": false,     // true表示是节假日，false表示是调休
     * "name": "国庆前调休",  // 节假日的中文名。如果是调休，则是调休的中文名，例如'国庆前调休'
     * "wage": 1,            // 薪资倍数，1表示是1倍工资
     * "after": false,       // 只在调休下有该字段。true表示放完假后调休，false表示先调休再放假
     * "target": '国庆节'     // 只在调休下有该字段。表示调休的节假日
     * }
     * }
     *
     * @param dateStr
     * @return
     */
    @Override
    public String queryWorkInfo(String dateStr) {
        StringBuilder sb = new StringBuilder();
        if (StrUtil.isBlank(dateStr)) {
            dateStr = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
        }
        String type = "工作日";
        String holidayName = "";
        String currentWeek = otherClient.queryWorkInfo(dateStr);
        if (StrUtil.isBlank(currentWeek)) {
            JSONObject jsonObject = JSONUtil.parseObj(currentWeek);
            if (Objects.nonNull(jsonObject)) {
                if (Objects.nonNull(jsonObject.get("type"))) {
                    JSONObject weekType = JSONUtil.parseObj(jsonObject.get("type"));
                    // 0-工作日、1-周末、2-节日、3-调休
                    type = weekType.get("type").toString();
                    if ("0".equals(type)) {
                        type = "工作日,努力的卷起来!";
                    } else if ("1".equals(type)) {
                        type = "周末,程序员好像没有周末!";
                    } else if ("2".equals(type)) {
                        type = "节日,程序员好像只有1024!";
                    } else if ("3".equals(type)) {
                        type = "调休,程序员好像没有调休!";
                    }
                }
                if (Objects.nonNull(jsonObject.get("holiday"))) {
                    JSONObject holidayJson = JSONUtil.parseObj(jsonObject.get("holiday"));
                    holidayName = holidayJson.get("name").toString();
                }
            }
        }
        sb.append("今天是").append(type);
        if (StrUtil.isNotBlank(holidayName)) {
            sb.append(",").append(holidayName);
        }
        sb.append(".");
        return sb.toString();
    }

    /**
     * {
     * "reason":"success",
     * "result":{
     * "date":"2022-12-05",
     * "week":"星期一",
     * "statusDesc":"工作日",
     * "status":null
     * },
     * "error_code":0
     * }
     *
     * @param dateStr
     * @return
     */
    @Override
    public String queryWorkInfoTwo(String dateStr) {
        StringBuilder sb = new StringBuilder();
        if (StrUtil.isBlank(dateStr)) {
            dateStr = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
        }
        String type = "工作日";
        String solarTerms = "";
        String holidayName = "";
        String currentWeek = otherClient.queryWorkInfoTwo(dateStr);
        if (StrUtil.isNotBlank(currentWeek)) {
            JSONObject jsonObject = JSONUtil.parseObj(currentWeek);
            if (Objects.nonNull(jsonObject)) {
                if (Objects.nonNull(jsonObject.get("result"))) {
                    JSONObject weekType = JSONUtil.parseObj(jsonObject.get("result"));
                    // 0-工作日、1-周末、2-节日、3-调休
                    type = weekType.get("statusDesc").toString();
                    if ("工作日".equals(type)) {
                        type = "工作日,努力的卷起来";
                    } else if ("周末".equals(type)) {
                        type = "周末,程序员好像没有周末";
                    } else if ("节假日".equals(type)) {
                        type = "节假日,程序员好像只有1024";
                    }
                    if (Objects.nonNull(weekType.get("term"))) {
                        solarTerms = weekType.get("term").toString();
                    }
                    if (Objects.nonNull(weekType.get("value"))) {
                        holidayName = weekType.get("value").toString();
                    }
                }
            }
        }
        sb.append("今天是").append(type);
        if (StrUtil.isNotBlank(solarTerms)) {
            sb.append(",节气:").append(solarTerms);
        }
        if (StrUtil.isNotBlank(solarTerms)) {
            sb.append(",节日:").append(holidayName);
        }
        sb.append(".");
        return sb.toString();
    }

    /**
     * 二次元图片API
     * <p>
     * https://t.lizi.moe/pc
     * http://www.98qy.com/sjbz/api.php
     * https://sex.nyan.xyz/api/v2/img
     * https://img.xjh.me/random_img.php
     * https://www.dmoe.cc/random.php
     * https://api.vvhan.com/api/girl
     */
    private List<String> newImages() {
        List imgUrls = new ArrayList<>();
        imgUrls.add("https://t.lizi.moe/pc");
        imgUrls.add("http://www.98qy.com/sjbz/api.php");
        imgUrls.add("https://sex.nyan.xyz/api/v2/img");
        imgUrls.add("https://img.xjh.me/random_img.php");
        imgUrls.add("https://www.dmoe.cc/random.php");
        //imgUrls.add("https://api.vvhan.com/api/girl");
        imgUrls.add("https://service-dn725wcs-1306777571.gz.apigw.tencentcs.com/release/");
        imgUrls.add("https://img.paulzzh.com/touhou/random");
        imgUrls.add("https://api.ghser.com/random/api.php");
        return imgUrls;
    }

    private String getRandomImg() {
        List<String> imageUrls = newImages();
        DCommonCode commonCode = codeService.getCommonCodeByCode(10006);
        if (Objects.nonNull(commonCode) && StrUtil.isNotBlank(commonCode.getContent())) {
            imageUrls = (List<String>) Convert.toList(commonCode.getContent());
        }
        StringBuilder sb = new StringBuilder();
        String imgUrl = imageUrls.get(RandomUtil.randomInt(imageUrls.size()));
        String imgBase = ImageUtil.getImgStrToBase64(imgUrl);
        sb.append(" <img src=" + imgBase + " + alt=\"二次元\" style=\"max-width:90%; max-height:2000px;\"/> ");
        /**
         * https://img.xjh.me/random_img.php
         */
        log.info("getRandomImg==> {}", imgUrl);
        return sb.toString();
    }

    /**
     * 合并多个天气
     *
     * @return
     */
    public String mergeManyWeatherDay(int day) {
        // 暂时 上海宝山区[101020300] 巫山[101042000] 泉州[101230501]
        StringBuilder sb = new StringBuilder();
        String shanghai = this.queryWeatherDay(101020300);
        if (StrUtil.isNotBlank(shanghai)) {
            sb.append(this.mergeWeatherStr(shanghai, day));
        }

        String quanzhou = this.queryWeatherDay(101230501);
        if (StrUtil.isNotBlank(quanzhou)) {
            sb.append(this.mergeWeatherStr(quanzhou, day));
        }

        String wushan = this.queryWeatherDay(101042000);
        if (StrUtil.isNotBlank(wushan)) {
            sb.append(this.mergeWeatherStr(wushan, day));
        }

        String xinning = this.queryWeatherDay(101250907);
        if (StrUtil.isNotBlank(xinning)) {
            sb.append(this.mergeWeatherStr(xinning, day));
        }

        return sb.toString();
    }

    /**
     * 拼接天气
     *
     * @param weatherStr
     * @return
     */
    public String mergeWeatherStr(String weatherStr, int day) {
        StringBuilder sb = new StringBuilder();
        sb.append("<br>");
        WeatherVo weather = JSONUtil.toBean(JSONUtil.parseObj(weatherStr), WeatherVo.class);
        // 地址
        sb.append("<p>").append(weather.getCityInfo().getParent()).append(weather.getCityInfo().getCity());
        // 获取当天日期
        String key = DateUtil.format(new Date(), "yyyy-MM-dd");
        if (day < 0) {
            WeatherVo.WeatherData.Yesterday yesterday = weather.getData().getYesterday();
            // 天气情况
            sb.append("<p>").append(yesterday.getType()).append("&nbsp;&nbsp;").append("最").append(yesterday.getHigh()).append("&nbsp;&nbsp;").append("最").append(yesterday.getLow()).append("&nbsp;&nbsp;").append(yesterday.getFx()).append(yesterday.getFl());
            sb.append("<p>").append(yesterday.getNotice());
            sb.append("<br>");
            return sb.toString();
        }
        // Forecast 当天+14天的天气List
        Map<String, WeatherVo.WeatherData.Forecast> forecastMap = new HashMap<>();
        List<WeatherVo.WeatherData.Forecast> forecasts = weather.getData().getForecast();
        forecasts.forEach(f -> {
            forecastMap.put(f.getYmd(), f);
        });
        if (day > 0) {
            key = DateUtil.format(DateUtil.offsetDay(new Date(), day), "yyyy-MM-dd");
        }
        WeatherVo.WeatherData.Forecast forecast = forecastMap.get(key);
        // 天气情况
        sb.append("<p>").append(forecast.getType()).append("&nbsp;&nbsp;").append("最").append(forecast.getHigh()).append("&nbsp;&nbsp;").append("最").append(forecast.getLow()).append("&nbsp;&nbsp;").append(forecast.getFx()).append(forecast.getFl());
        sb.append("<p>").append(forecast.getNotice());
        sb.append("<br>");
        return sb.toString();
    }

    /**
     * 合并网易云评论
     *
     * @return
     */
    public String mergeWYYComment(String redisCommentKey, StringBuilder sb) {
        String hotComment;
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            // 云音乐热歌榜
            hotComment = shaDiaoClient.queryWyiYunTxt(1, 5);
            if (StrUtil.isNotBlank(hotComment)) {
                JSONObject jsonObject = JSONUtil.parseObj(hotComment);
                // 解析json获取评论
                String data = jsonObject.get("data").toString();
                JSONArray jsonArray = JSONUtil.parseArray(data);
                for (int i = 0; i < jsonArray.size(); i++) {
                    String txt = jsonArray.getJSONObject(i).get("content").toString();
                    stringBuilder.append(" <p> ").append(seq++).append(".").append(txt);
                    if (StrUtil.isNotBlank(txt)) {
                        redisUtil.lSet(redisCommentKey, txt);
                    }
                }
            }
        } catch (Exception e) {
            if (redisUtil.hasKey(redisCommentKey)) {
                stringBuilder = new StringBuilder();
                long size = redisUtil.lGetListSize(redisCommentKey);
                int randomIndex = RandomUtil.randomInt(5, (int) size);
                List<Object> o = redisUtil.lGet(redisCommentKey, randomIndex - 5, randomIndex);
                if (o != null) {
                    for (int i = 0; i < o.size(); i++) {
                        String txt = o.get(i).toString();
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(txt);
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

    /**
     * 合并诗词
     *
     * @return
     */
    public String mergePoetryComment(String redisCommentKey, StringBuilder sb) {
        String poetryComment;
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            for (int i = 0; i < 5; i++) {
                poetryComment = shaDiaoClient.queryRandomPoetryTxt();
                if (StrUtil.isNotBlank(poetryComment)) {
                    StringBuilder dataStr = new StringBuilder();
                    JSONObject v1 = JSONUtil.parseObj(poetryComment);
                    String content = v1.getStr("content");
                    String origin = v1.getStr("origin");
                    String category = v1.getStr("category");
                    String author = v1.getStr("author");
                    dataStr.append(content).append("\n").append("[").append(origin).append("-").append(author).append("-").append(category).append("]");
                    redisUtil.sSet(redisCommentKey, poetryComment);
                    stringBuilder.append(" <p> ").append(seq++).append(".");
                    stringBuilder.append(dataStr);
                }
            }
        } catch (Exception e) {
            if (redisUtil.hasKey(redisCommentKey)) {
                stringBuilder = new StringBuilder();
                long size = redisUtil.lGetListSize(redisCommentKey);
                int randomIndex = RandomUtil.randomInt(5, (int) size);
                List<Object> o = redisUtil.lGet(redisCommentKey, randomIndex - 5, randomIndex);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        StringBuilder dataStr = new StringBuilder();
                        JSONObject v1 = JSONUtil.parseObj(o.get(k).toString());
                        String content = v1.getStr("content");
                        String origin = v1.getStr("origin");
                        String category = v1.getStr("category");
                        String author = v1.getStr("author");
                        dataStr.append(content).append("\n").append("[").append(origin).append("-").append(author).append("-").append(category).append("]");
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(dataStr);
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

    /**
     * 合并傻屌文案
     *
     * @param type     0-彩虹屁 1-毒鸡汤 2-朋友圈
     * @param redisKey
     * @param sb
     * @return
     */
    public String mergeShaDiaoTxt(int type, String redisKey, StringBuilder sb) {
        String txt = "";
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            for (int i = 0; i < 5; i++) {
                if (type == 0) {
                    txt = shaDiaoClient.queryShaDiaoChpTxt();
                } else if (type == 1) {
                    txt = shaDiaoClient.queryShaDiaoDuTxt();
                } else if (type == 2) {
                    txt = shaDiaoClient.queryShaDiaoFriendTxt();
                }
                if (StrUtil.isNotBlank(txt)) {
                    JSONObject v1 = JSONUtil.parseObj(txt);
                    String t1 = v1.get("data").toString();
                    JSONObject v2 = JSONUtil.parseObj(t1);
                    txt = v2.get("text").toString();
                    redisUtil.sSet(redisKey, txt);
                    stringBuilder.append(" <p> ").append(seq++).append(".");
                    stringBuilder.append(txt);
                }
            }
        } catch (Exception e) {
            if (redisUtil.hasKey(redisKey)) {
                stringBuilder = new StringBuilder();
                List<Object> o = redisUtil.sGetRandom(redisKey, 5);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(o.get(k).toString());
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

    public String mergeDogTxtTwo(String redisDogKey, StringBuilder sb) {
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        if (redisUtil.hasKey(redisDogKey)) {
            stringBuilder = new StringBuilder();
            List<Object> o = redisUtil.sGetRandom(redisDogKey, 5);
            if (o != null) {
                for (int k = 0; k < o.size(); k++) {
                    stringBuilder.append(" <p> ").append(seq++).append(".").append(o.get(k).toString());
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

    public String mergePlayBoyTxt(String redisPlayKey, StringBuilder sb) {
        String txt = "";
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            txt = shaDiaoClient.queryPlayboyTxt();
            if (StrUtil.isNotBlank(txt)) {
                JSONObject v1 = JSONUtil.parseObj(txt);
                JSONArray v2 = v1.getJSONArray("returnObj");
                if (v2.size() > 0) {
                    for (int i = 0; i < v2.size(); i++) {
                        String content = v2.get(i).toString();
                        stringBuilder.append(" <p> ").append(seq++).append(".");
                        stringBuilder.append(content);
                        redisUtil.sSet(redisPlayKey, content);
                    }
                } else {
                    throw new Exception("api error");
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            if (redisUtil.hasKey(redisPlayKey)) {
                stringBuilder = new StringBuilder();
                List<Object> o = redisUtil.sGetRandom(redisPlayKey, 5);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(o.get(k).toString());
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }


    /**
     * 绿茶语录
     * <p>
     * {"code":200,"message":"","returnObj":{"id":"e41e3508-c2f8-40e0-a1be-2201b0510a66","content":"曾经沧海难为水，除却巫山不是云","likeCount":32,"dislikeCount":29}}
     *
     * @param redisTeaKey
     * @param sb
     * @return
     */
    public String mergeGreenTeaTxt(String redisTeaKey, StringBuilder sb) {
        String txt = "";
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            txt = shaDiaoClient.queryGreenTeaTxt();
            if (StrUtil.isNotBlank(txt)) {
                JSONObject v1 = JSONUtil.parseObj(txt);
                JSONArray v2 = v1.getJSONArray("returnObj");
                if (v2.size() > 0) {
                    for (int i = 0; i < v2.size(); i++) {
                        String content = v2.get(i).toString();
                        stringBuilder.append(" <p> ").append(seq++).append(".");
                        stringBuilder.append(content);
                        redisUtil.sSet(redisTeaKey, content);
                    }
                } else {
                    throw new Exception("api error");
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            if (redisUtil.hasKey(redisTeaKey)) {
                stringBuilder = new StringBuilder();
                List<Object> o = redisUtil.sGetRandom(redisTeaKey, 5);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(o.get(k).toString());
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }


    /**
     * 合并新闻信息
     *
     * @param redisNewsKey
     * @param sb
     * @return
     */
    public String mergeNewsTxt(String redisNewsKey, StringBuilder sb) {
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        // type top(推荐,默认)guonei(国内)guoji(国际)yule(娱乐)tiyu(体育)junshi(军事)keji(科技)
        // caijing(财经)youxi(游戏)qiche(汽车)jiankang(健康)
        Map typeMap = MapUtil.of(new String[][] {  {"guonei", "国内新闻"},  {"guoji", "国际新闻"}, {"junshi", "军事新闻"}, {"qiche", "汽车新闻"} });
        for (Iterator<Map.Entry<String, String>> entries = typeMap.entrySet().iterator(); entries.hasNext(); ) {
            Map.Entry<String, String> entry = entries.next();
            buildNewsTxt(seq, redisNewsKey, entry.getKey(), entry.getValue(), stringBuilder);
            seq = seq + 10;
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

    private void buildNewsTxt(Integer seq, String redisNewsKey, String type, String headTitle, StringBuilder sb) {
        String txt = "";
        StringBuilder stringBuilder = new StringBuilder();
        redisNewsKey = redisNewsKey + ":" + type;
        try {
            stringBuilder.append(" <p> ").append("[").append(headTitle).append("]");
            txt = otherClient.queryNewsList(type);
            if (StrUtil.isNotBlank(txt)) {
                JSONObject v1 = JSONUtil.parseObj(txt);
                String t1 = v1.get("result").toString();
                JSONObject v2 = JSONUtil.parseObj(t1);
                String t2 = v2.get("data").toString();
                JSONArray v3 = JSONUtil.parseArray(t2);
                if (v3.size() > 0) {
                    for (int i = 0; i < v3.size(); i++) {
                        JSONObject v4 = v3.getJSONObject(i);
                        String title = v4.getStr("title");
                        String auth = v4.getStr("author_name");
                        String url = v4.getStr("url");
                        stringBuilder.append(" <p> ").append(seq++).append(".");
                        stringBuilder.append("<a href='").append(url).append("'>").append(title).append("-").append(auth).append("<a>");
                        redisUtil.sSet(redisNewsKey, v4);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            if (redisUtil.hasKey(redisNewsKey)) {
                stringBuilder = new StringBuilder();
                List<Object> o = redisUtil.sGetRandom(redisNewsKey, 10);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        JSONObject v4 = JSONUtil.parseObj(o.get(k).toString());
                        String title = v4.getStr("title");
                        String auth = v4.getStr("author_name");
                        String url = v4.getStr("url");
                        stringBuilder.append(" <p> ").append(seq++).append(".");
                        stringBuilder.append("<a href='").append(url).append("'>").append(title).append("-").append(auth).append("<a>");
                    }
                }
            }
        }
        sb.append(stringBuilder);
    }

    public String mergeTodayNewsTxt(String redisTodayNewsKey, StringBuilder sb) {
        String txt = "";
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            txt = otherClient.queryTodayNewsList();
            if (StrUtil.isNotBlank(txt)) {
                JSONObject v1 = JSONUtil.parseObj(txt);
                String t1 = v1.get("result").toString();
                JSONObject v2 = JSONUtil.parseObj(t1);
                String t2 = v2.get("list").toString();
                JSONArray v3 = JSONUtil.parseArray(t2);
                if (v3.size() > 0) {
                    for (int i = 0; i < v3.size(); i++) {
                        JSONObject v4 = v3.getJSONObject(i);
                        String title = v4.getStr("title");
                        String content = v4.getStr("digest");
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(title).append("<p> ").append(content);
                        redisUtil.sSet(redisTodayNewsKey, JSONUtil.toJsonStr(v4));
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            if (redisUtil.hasKey(redisTodayNewsKey)) {
                stringBuilder = new StringBuilder();
                List<Object> o = redisUtil.sGetRandom(redisTodayNewsKey, 10);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        JSONObject v4 = JSONUtil.parseObj(o.get(k).toString());
                        String title = v4.getStr("title");
                        String content = v4.getStr("digest");
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(title).append("<p> ").append(content);
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

    public String mergeJestTxt(String redisJestKey, StringBuilder sb) {
        String txt = "";
        Integer seq = 1;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            long time = System.currentTimeMillis() / 1000;
            txt = otherClient.queryJestList(RandomUtil.randomInt(1, 20), time);
            if (StrUtil.isNotBlank(txt)) {
                JSONObject v1 = JSONUtil.parseObj(txt);
                String t1 = v1.get("result").toString();
                JSONObject v2 = JSONUtil.parseObj(t1);
                String t2 = v2.get("data").toString();
                JSONArray v3 = JSONUtil.parseArray(t2);
                if (v3.size() > 0) {
                    for (int i = 0; i < v3.size(); i++) {
                        JSONObject v4 = v3.getJSONObject(i);
                        String content = v4.getStr("content");
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(content);
                        redisUtil.sSet(redisJestKey, content);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            if (redisUtil.hasKey(redisJestKey)) {
                stringBuilder = new StringBuilder();
                List<Object> o = redisUtil.sGetRandom(redisJestKey, 10);
                if (o != null) {
                    for (int k = 0; k < o.size(); k++) {
                        stringBuilder.append(" <p> ").append(seq++).append(".").append(o.get(k).toString());
                    }
                }
            }
        }
        sb.append(stringBuilder);
        return sb.toString();
    }

}
